<?php
/**
 *
 *
 * @author
 * @version
 */
class User_IndexController extends Zend_Controller_Action {

	public function init() {
		$this->_helper->layout->setLayout('login');
	}


	public function loginAction() {
		$this->_helper->layout->setLayout('login');

		$this->view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
		$this->view->jQuery()
			->enable()->uiEnable()
			->setLocalPath('/cms/res/jui/jquery-1.7.2.min.js')
			->addStylesheet('/cms/res/jui/zen/jquery-ui-1.8.21.custom.css')
			->addJavascriptFile('/cms/res/jui/i18n/jquery.ui.datepicker-ru.js')
			->setUiLocalPath('/cms/res/jui/jquery-ui-1.8.14.custom.min.js');
		
		$f = new Zend_Filter_StripTags ();
		$login = $f->filter ( trim ( $this->_getParam ( 'user_login' ) ) );
		$password = $f->filter ( trim ( $this->_getParam ( 'user_password' ) ) );
		if (($this->_hasParam ( 'remember' )) && ($this->_getParam ( 'remember' )) == 'on') {
			$rem = true;
		} else {
			$rem = false;
		}
		if ($this->_request->isPost ()) {
			if (empty ( $login )) {
				if ($this->_request->isXmlHttpRequest ()) {
					$this->_helper->json ( array ('text' => 'Вы не ввели Логин', 'success' => false ) );
				} else {
					$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' => 'Вы не ввели Логин', 'type' => 'error' ) );
					$this->_redirect ( $_SERVER ['REQUEST_URI'] );
				}
			}
			if (empty ( $password )) {
				if ($this->_request->isXmlHttpRequest ()) {
					$this->_helper->json ( array ('text' => 'Вы не ввели Пароль', 'success' => false ) );
				} else {
					$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' => 'Вы не ввели Пароль', 'type' => 'error' ) );
					$this->_redirect ( $_SERVER ['REQUEST_URI'] );
				}
			}
			$res = Zen_User::login ( $login, $password, $rem );
			if ($res == false) {
				if ($this->_request->isXmlHttpRequest ()) {
					$this->_helper->json ( array ('text' => 'Не правильный Логин или Пароль', 'success' => false ) );
				} else {
					$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' => 'Не правильный Логин или Пароль', 'type' => 'error' ) );
					$this->_redirect ( $_SERVER ['REQUEST_URI'] );
				}
			} else {
				Log_Model_Logger::log('Login '.$login, Zend_Log::NOTICE, array());
				if ($this->_request->isXmlHttpRequest ()) {
					$this->_helper->json ( array ('success' => true ) );
				} else {
					$acl  = Zen_Acl::getInstance();
					$user = Zen_User::getOne(Zen_User::getId());
					if ($acl->isAllowed($user ['role'],'adminka')){
						$this->_redirect ( '/admin' );
					}
					else {
						$this->_redirect ('/');
					}
				}
			}
		}
	}

	public function logoutAction() {
		Zen_User::logout ();
		unset ( $_SESSION ['login_back'] );
		if(isset($_SERVER['HTTP_REFERER'])){
			$this->_redirect ($_SERVER['HTTP_REFERER']);
		}else{
		$this->_redirect ( '/login' );
		}
	}

	public function remAction() {
		$res = array ();
		if ($this->_request->isPost ()) {
			if ($this->_hasParam('email')&&($this->_getParam('email')!="")) {
				$email = $this->_getParam('email');
					$model = new User_Model_Users();
					$email=trim($this->_getParam('email'));

					$user = $model->select()->setColumns(array('email','id','role','name'))->getOne ( "`email`='" . $email . "'" );
					if ($user) {
						$new_pass = Zen_Password::generate ( 8 );
						$hash=$user['id'].$new_pass.date('Y-m-d H:i:s');
						$hash=Zen_User::hashpass($hash);

						$params = array('new_pass_hash'=>$hash,'new_pass'=>$new_pass);
						$id = $model->update ($user['id'],$params );

						Zen_User::rem ($user['id']);
						$res ['success'] = true;
						$res['error']= 'Новый пароль отправлен на ваш Email адрес';
						$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' =>$res['error'], 'type' => 'alert' ) );

					} else {
						$res ['success'] = false;
						$res['error']= 'Пользователь с таким адресом не зарегистрирован';
						$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' =>$res['error'], 'type' => 'error' ) );

					}

			}else{
						$res['error']= 'Вы не ввели Email';
						$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' =>$res['error'], 'type' => 'error' ) );

			}
			$this->_redirect ( $_SERVER ['REQUEST_URI'] );
		}
	}


	public function newpassAction() {
		$hash = trim($this->_getParam('hash'));
		$model = new User_Model_Users ();
		$user=$model->select()->setColumns(array('login','email','id','role','name','new_pass_hash','pass','new_pass'))->getOne("`new_pass_hash`='".$hash."'");
		if($user){
			if($model->update($user['id'],array('pass'=>$user['new_pass'],'new_pass_hash'=>'','new_pass'=>'')))
			{
				Zen_User::login($user['login'],$user['new_pass'],true);
				echo "<h2>Новый пароль применён</h2>";
				echo "Ваш логин:".$user['login']."<br/>";
				echo "Ваш пароль:".$user['pass']."<br/>";
				echo "<a href='/profile'>редактировать профиль</a>"."<br/>";
			}else{
				echo "<h2>Ваш пароль уже изменён на новый</h2>";
			}
		}else{
				echo "<h2>Ваш пароль уже изменён на новый</h2>";
		}
	}



	public function profileAction() {
		$this->_helper->layout->setLayout('admin');
		if (Zen_User::isLoged ()) {
			$form = new User_Form_Profile ();
			$form->getElement ( 'submit' )->setLabel ( 'Сохранить изменения' );

			$id = Zen_User::getId ();
			$user = Zen_User::getOne ( $id );
			unset ( $user ['pass'] );
			if ( $user ) $form->setDefaults ( $user );
			if ($this->_request->isPost ()) {
				$params = $this->_getAllParams ();
				if (trim ( $params ['pass'] ) == '') {
					$form->getElement ( 'pass' )->setRequired ( false );
					$form->getElement ( '_confirm_approve' )->setRequired ( false );

				}
				if ($params ['login'] == $user ['login']) {
					$form->getElement ( 'login' )->removeValidator ( 'NoDbRecordExists' );
				}
				if ($params ['email'] == $user ['email']) {
					$form->getElement ( 'email' )->removeValidator ( 'NoDbRecordExists' );
				}
				if ($form->isValid ( $params )) {


					$model = new User_Model_Users ( $params );
					$params = $form->getValues ();

					if (trim ( $params ['pass'] ) == '') {
						unset($params ['pass']);
					}


					$id = $model->update ( $id, $params );
					if ($id) {

						$this->_helper->FlashMessenger->setNamespace ( 'messages' )->addMessage ( array ('text' => 'Изменния сохранены', 'type' => 'alert' ) );
						$this->_redirect ( '/profile' );
					}
				}
			}
			$this->view->form = $form;
		}else{
			$this->_redirect ( '/login' );
		}
	}



	public function errorAction(){
			$this->_helper->layout->setLayout('login');
	}

}
